import { HttpClient } from '@angular/common/http';
import { Component, ViewChild } from '@angular/core';
import { TableWidthConfig, DataTableComponent, DrawerService, IDrawerOpenResult, DialogService } from '@devui';
import { SalePayment } from 'src/app/@core/data/sale';
import { DataSharingService } from 'src/app/@core/services/dataSharing/data-sharing.service';
import { LogComponent } from 'src/app/@shared/components/log/log.component';
import { environment } from 'src/environments/environment';
import { ReviewDocComponent } from '../../basic-data/user-center/review-doc/review-doc.component';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { Router } from '@angular/router';
import { SalesService } from 'src/app/@core/services/sales/sales.service';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import * as mockSalesPaymentData from '../../../@core/data/mock-sales-payment.json';
@Component({
  selector: 'app-sales-payment',
  templateUrl: './sales-payment.component.html',
  styleUrls: ['./sales-payment.component.scss']
})
export class SalesPaymentComponent {
pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20,
  };
  pageSizeOptions = [10, 20, 30, 50, 100];
  SalePayment: SalePayment = {
    salePaymentId: 0, // 销售收款单ID
    paymentNum: '', // 收款单号
    paymentDate: new Date(), // 收款日期
    customerID: 0, // 客户ID
    customerName: '', // 客户名称
    customerShortName: '', // 客户简称
    customerContact: '', // 客户联系人
    contactInfo: '', // 联系方式
    salesmanName: '', // 业务员
    department: '', // 部门
    receiptAmount: 0, // 实收金额
    discountAmount: 0, // 优惠金额
    actualAmount: 0, // 应收金额
    remainingAmount: 0, // 剩余金额
    remark: '', // 备注
    status: '待确认', // 状态
    isConfirmed: false, // 是否确认收款
    creationDate: new Date(), // 创建日期
    creator: '', // 创建者
    confirmDate: null, // 确认日期
    confirmer: '', // 确认人
    saleOrderNum: '', // 关联销售订单号
    
  };
  tableData = [];
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '操作',
        fieldType: 'customized',
        width: '250px',
        fixedLeft: '80px',
      },
      {
        field: 'paymentNum',
        header: '收款单号',
        fieldType: 'text',
        fixedLeft: '410px',
      },
      {
        field: 'paymentDate',
        header: '收款日期',
        fieldType: 'text',
      },
      {
        field: 'customerName',
        header: '客户全称',
        fieldType: 'text',
      },
      {
        field: 'customerShortName',
        header: '客户简称',
        fieldType: 'text',
      },
      {
        field: 'salesmanName',
        header: '业务员',
        fieldType: 'text',
      },
      {
        field: 'department',
        header: '部门',
        fieldType: 'text',
      },
      {
        field: 'settlementMethod',
        header: '结算方式',
        fieldType: 'text',
      },
      {
        field: 'paymentType',
        header: '收款方式',
        fieldType: 'text',
      },
      {
        field: 'receiptAmount',
        header: '实收金额',
        fieldType: 'text',
      },
      {
        field: 'actualAmount',
        header: '应收金额',
        fieldType: 'text',
      },
      {
        field: 'remainingAmount',
        header: '剩余金额',
        fieldType: 'text',
      },
      {
        field: 'remark',
        header: '备注',
        fieldType: 'text',
      },
      {
        field: 'creator',
        header: '制单人',
        fieldType: 'text',
      },
      {
        field: 'creationDate',
        header: '制单日期',
        fieldType: 'text',
      },
      {
        field: 'status',
        header: '状态',
        fieldType: 'text',
        fixedRight: '0px',
      },
    ],
  } //表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px',
    },
    {
      field: '操作',
      width: '330px',
    },
    {
      field: 'paymentNum',
      width: '150px',
    },
    {
      field: 'paymentDate',
      width: '150px',
    },
    {
      field: 'customerName',
      width: '150px',
    },
    {
      field: 'customerShortName',
      width: '150px',
    },
    {
      field: 'salesmanName',
      width: '150px',
    },
    {
      field: 'department',
      width: '150px',
    },
    {
      field: 'settlementMethod',
      width: '150px',
    },
    {
      field: 'paymentType',
      width: '150px',
    },
    {
      field: 'receiptAmount',
      width: '150px',
    },
    {
      field: 'actualAmount',
      width: '150px',
    },
    {
      field: 'remainingAmount',
      width: '150px',
    },
    {
      field: 'remark',
      width: '150px',
    },
    {
      field: 'creator',
      width: '150px',
    },
    {
      field: 'creationDate',
      width: '150px',
    },
    {
      field: 'status',
      width: '150px',
    },
  ] //表格宽度配置
  tableWidthConfig2: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px',
    },
    {
      field: '物料编码',
      width: '200px',
    },
    {
      field: '图片',
      width: '150px',
    },
    {
      field: '物料名称',
      width: '150px',
    },
    {
      field: '规格型号',
      width: '150px',
    },
    {
      field: '物料描述',
      width: '150px',
    },
    {
      field: '发货日期',
      width: '200px',
    },
    {
      field: '已发货数量',
      width: '150px',
    },
    {
      field: '结算数量',
      width: '170px',
    },
    {
      field: '单位',
      width: '150px',
    },
    {
      field: '单价(含税)',
      width: '170px',
    },
    {
      field: '单价（不含税）',
      width: '150px',
    },
    {
      field: '税率（%）',
      width: '170px',
    },
    {
      field: '折扣（%）',
      width: '150px',
    },
    {
      field: '折扣单价（含税）',
      width: '150px',
    },
    {
      field: '含税金额',
      width: '150px',
    },
    {
      field: '不含税金额',
      width: '150px',
    },
    {
      field: '税额',
      width: '150px',
    },
    {
      field: '折扣不含税金额',
      width: '150px',
    },
    {
      field: '折扣含税金额',
      width: '150px',
    },
    {
      field: '折扣税额',
      width: '150px',
    },
    {
      field: '来源订单号',
      width: '150px',
    },
    {
      field: '来源发货单号',
      width: '150px',
    },
    {
      field: '备注',
      width: '150px',
    },
  ]
  msgs: { severity: any; summary: any; content: any }[];
  @ViewChild(DataTableComponent, { static: true })
  datatable: DataTableComponent;
  checkedIds: any = [];
  fifter = {
    PaymentNum: '',
    CustomerName: '',
    CustomerShortName: '',
    StartTime: '',
    EndTime: '',
    SalesmanName: '',
    Department: '',
    PaymentType: '',
    Status: '',
    PageNumber: 1, // 通常分页参数的初始值
    PageSize: 20, // 假设默认页面大小为20
  };
  date = [];
  Customer: any;
  splitBarSize = '0px';
  partDetailHeight = '100%';
  showDetailId: any;
  selectedRowIndex: any;
  partDetail: any = [];
  checkedCodes: any=[]
  constructor(
    private SharedMethodService: SharedMethodService,
    private Router: Router,
    private SalesService: SalesService,
    private DialogService: DialogService,
    private dataSharingService: DataSharingService,
    private CustomerService: CustomerService,
    private drawerService: DrawerService,
    private ReviewRolesService: ReviewRolesService,
    private http: HttpClient
  ){}
  ngOnInit(): void {
    // 从JSON文件加载销售收款单数据
    this.tableData = (mockSalesPaymentData as any).default || mockSalesPaymentData;
    this.pager.total = this.tableData.length;
    this.CustomerService.GetPagedCustomer({
      PageNumber: 1,
      PageSize: 999,
    }).subscribe((data: any) => {
      this.Customer = data.items;
    })
  }
  filter() {
    this.SalesService.GetSaleOrders(this.fifter).subscribe((data: any) => {
      this.tableData = data.items;
      this.pager.total = data.totalCount;
      console.log(this.showDetailId);
      if (this.showDetailId) {
        this.showDetail(
          this.tableData.find(
            (item: any) => item.saleOrderId === this.showDetailId
          ),
          this.selectedRowIndex
        );
      }
    });
  }
  filter2() {
    this.fifter.PageNumber = 1;
    this.filter();
  }
  statusOption = {};
  reset() {
    this.fifter = {
      PaymentNum: '',
      CustomerName: '',
      CustomerShortName: '',
      StartTime: '',
      EndTime: '',
      SalesmanName: '',
      Department: '',
      PaymentType: '',
      Status: '',
      PageNumber: 1,
      PageSize: 20,
    };
    this.date = [];
    this.filter();
  }
  creat() {
    this.Router.navigate(['/pages/sales-master/add-sales-payment']);
  }
  edit(id: any) {
    this.Router.navigate(['/pages/sales-master/sales-payment/edit', id]);
  }
  delete(id?: any, dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '400px',
      backdropCloseable: true,
      data: '',
      title: '删除',
      content: '删除后将无法恢复该数据！',
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (id) {
              this.SalesService.DeleteSaleOrders([id]).subscribe(
                (data: any) => {
                  this.showToast('success', '成功', '删除成功');
                  this.SalesService.GetSaleOrders(this.fifter).subscribe(
                    (data: any) => {
                      this.tableData = data.items;
                      this.pager.total = data.totalCount;
                    }
                  );
                },
                (error) => {
                  if(error.status==404){
                    this.showToast('error', '失败', '服务器连接失败');
                  }else{
                    this.showToast('error', '失败', error.error);
                  }
                }
              );
            } else {
              this.SalesService.DeleteSaleOrders(this.checkedIds).subscribe(
                (data: any) => {
                  this.showToast('success', '成功', '删除成功');
                  this.checkedIds = [];
                  this.SalesService.GetSaleOrders(this.fifter).subscribe(
                    (data: any) => {
                      this.tableData = data.items;
                      this.pager.total = data.totalCount;
                    }
                  );
                },
                (error) => {
                  if(error.status==404){
                    this.showToast('error', '失败', '服务器连接失败');
                  }else{
                    this.showToast('error', '失败', error.error);
                  }
                }
              );
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  onRowCheckChange(
    checked: any,
    rowIndex: any,
    nestedIndex: any,
    rowItem: { $checked: any; $halfChecked: boolean }
  ) {
    this.SharedMethodService.onRowCheckChange(
      checked,
      rowIndex,
      nestedIndex,
      rowItem,
      this.datatable
    );
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'saleSettlementId'
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'settlementNum'
    ).subscribe((data: any) => {
      this.checkedCodes = data;
    });
  } //获取选中行
  cleared() {
    this.SharedMethodService.cleared(
      this.checkedIds,
      this.tableData,
      this.datatable
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
  } //清空选中行
  pageIndexChange($event: any) {
    this.filter();
  } //切换页码
  pageSizeChange($event: any) {
    this.filter();
  } //改变每页显示数量
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  dateChange() {
    this.fifter.StartTime = this.date[0]
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .replace(/\//g, '/');
    this.fifter.EndTime = this.date[1]
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .replace(/\//g, '/');
  }
  settled(id: any) {
    // 模拟结算操作
    const settlement = this.tableData.find((item: any) => item.saleSettlementId === id);
    if (settlement) {
      settlement.isSettled = true;
      settlement.actualPaymentAmount = settlement.totalAmountWithTax;
      settlement.remainingAmount = 0;
      this.showToast('success', '成功', '结算成功');
    }
  } //结算
  unSettled(id: any) {
    // 模拟反结算操作
    const settlement = this.tableData.find((item: any) => item.saleSettlementId === id);
    if (settlement) {
      settlement.isSettled = false;
      settlement.actualPaymentAmount = settlement.advancePaymentAmount;
      settlement.remainingAmount = settlement.totalAmountWithTax - settlement.advancePaymentAmount;
      this.showToast('success', '成功', '反结算成功');
    }
  } //反结算
  CheckedRows = [];
  getCheckedRowsData() {
    this.SharedMethodService.getCheckedRowsData(this.datatable).subscribe(
      (data: any) => {
        this.CheckedRows = data;
      }
    );
  } //获取选中行
  downloadTemplate() {
    this.SalesService.DownloadSaleOrderFileModel().subscribe((data: any) => {
      const blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '销售订单模板.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    });
  }
  file: any;
  importSalesQuotation(event: any) {
    this.file = event.target.files[0];
    this.SalesService.ImportSaleOrderFromExcel(this.file).subscribe(
      (data: any) => {
        this.SalesService.GetSaleOrders(this.fifter).subscribe((data: any) => {
          this.tableData = data.items;
          this.pager.total = data.totalCount;
          this.showToast('success', '成功', '导入成功');
        });
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
        this.fileInput2.nativeElement.value = '';
      }
    );
  }
  @ViewChild('fileInput2') fileInput2: any;
  onButtonClick() {
    this.fileInput2.nativeElement.click();
  }
  download() {
    this.SalesService.DownloadSaleOrderFile().subscribe((data: any) => {
      const blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '销售订单单据.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    });
  }
  results: IDrawerOpenResult;
  allLog() {
    this.SalesService.GetAllSaleOrderLogs({
      PageNumber: 1,
      PageSize: 999,
    }).subscribe((data: any) => {
      const logData = data.items;
      const columns = [
        {
          field: '销售顶单',
          header: '销售顶单',
          fieldType: 'text',
        },
        {
          field: 'content',
          header: '日志内容',
          fieldType: 'text',
        },
        {
          field: '执行人',
          header: '执行人',
          fieldType: 'text',
        },
        {
          field: '执行时间',
          header: '执行时间',
          fieldType: 'text',
        }
      ];
      this.results = this.drawerService.open({
        drawerContentComponent: LogComponent,
        width: '40%',
        data: { data: logData, columns: columns },
        zIndex: 1000,
        isCover: false,
        fullScreen: true,
        backdropCloseable: true,
        escKeyCloseable: true,
        position: 'right',
        resizable: true,
        onClose: () => {},
      });
    });
  }
  GetLogsById(id: any) {
    // 模拟获取结算单日志
    const logData = [
      {
        '销售结算单': `JS${id}`,
        content: '结算单创建',
        '执行人': '张三',
        '执行时间': '2025-01-15 10:30:00'
      },
      {
        '销售结算单': `JS${id}`,
        content: '提交审核',
        '执行人': '李四',
        '执行时间': '2025-01-15 14:20:00'
      }
    ];
    const columns = [
      {
        field: '销售结算单',
        header: '销售结算单',
        fieldType: 'text',
      },
      {
        field: 'content',
        header: '日志内容',
        fieldType: 'text',
      },
      {
        field: '执行人',
        header: '执行人',
        fieldType: 'text',
      },
      {
        field: '执行时间',
        header: '执行时间',
        fieldType: 'text',
      }
    ];
    this.results = this.drawerService.open({
      drawerContentComponent: LogComponent,
      width: '40%',
      data: { data: logData, columns: columns },
      zIndex: 1000,
      isCover: false,
      fullScreen: true,
      backdropCloseable: true,
      escKeyCloseable: true,
      position: 'right',
      resizable: true,
      onClose: () => {},
    });
  }
  showDetail(data: any, rowIndex: any) {
    this.showDetailId = data.saleSettlementId;
    (this.partDetail = data.saleSettlementParts), (this.partDetailHeight = '75%');
    this.splitBarSize = '10px';
    this.selectedRowIndex = rowIndex;
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + url);
    return urls;
  }
  launchReview() {
    const invalidStatus = this.CheckedRows.some(row => row.status === '审核通过' || row.status === '审核中')
    if (invalidStatus) {
        this.showToast('error', '错误', '所选单据已发起审核');
        return
    }
    if (this.checkedCodes.length < 1) {
      this.showToast('error', '错误', '请选择要发起审核的单据');
      return;
    }
    this.ReviewRolesService.StartApprovalFlow('销售结算单审核流配置',this.checkedCodes).subscribe(
      (res: any) => {
        this.showToast('success', '成功', res);
        this.filter();
        this.checkedIds = [];
        this.checkedCodes = [];
      },
      (error: any) => {
        this.showToast('error', '错误', error.error);
      }
    );
  }
  clickCode(code: string, type: string, status?: string, dialogtype?: string) {
    let data = {
      code: code,
      type: type,
      disPlay: false,
    };
    const results = this.DialogService.open({
      id: 'custom',
      width: '90vw',
      maxHeight: '90vh',
      backdropCloseable: true,
      content: ReviewDocComponent,
      dialogtype: dialogtype,
      data:data,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '通过',
          handler: ($event: Event) => {
            if(results.modalContentInstance.approvalNodeId){
            this.ReviewRolesService.ApproveNode(
              results.modalContentInstance.approvalNodeId,
              code
            ).subscribe((res: any) => {
              results.modalInstance.hide();
              this.showToast('success', '成功', '审批成功');
              this.filter();
            },error=>{
              this.showToast('error', '错误', error.error || '网络连接错误');
            }
          );
          }
          else{
            this.showToast('error', '错误', '没有需要审批的节点');
          }
          },
        },
        {
          cssClass: 'danger',
          text: '驳回',
          handler: ($event: Event) => {
            if(results.modalContentInstance.approvalNodeId){
              console.log()
            if(results.modalContentInstance.reason){
              this.ReviewRolesService.RejectNode(
                results.modalContentInstance.approvalNodeId,
                code,
                results.modalContentInstance.reason
              ).subscribe(
                (res) => {
                  this.showToast('success', '成功', '审批成功');
                  results.modalInstance.hide();
                  this.filter();
                },
                (error: any) => {
                  this.showToast(
                    'error',
                    '错误',
                    error.error || '网络连接错误'
                  );
                }
              );
            }else{
              data.disPlay = true
              this.showToast('warn', '警告', '请填写驳回原因');
            }
          }else{
            this.showToast('error', '错误', '没有需要审批的节点');
          }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  getImagesArray2(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl +'/' + url);
    return urls;
  }
  // 确认收款
  confirmPayment(paymentId: number) {
    const results = this.DialogService.open({
      id: 'confirm-payment-dialog',
      width: '400px',
      maxHeight: '600px',
      title: '确认收款',
      content: '确定要确认此笔收款吗？',
      dialogtype: 'standard',
      buttons: [
        {
          cssClass: 'primary',
          text: '确认',
          disabled: false,
          handler: ($event: Event) => {
            // 在实际项目中这里应该调用API
            const payment = this.tableData.find((item: any) => item.salePaymentId === paymentId);
            if (payment) {
              payment.isConfirmed = true;
              payment.status = '已确认';
              payment.confirmDate = new Date();
              payment.confirmer = '财务经理-刘总';

              this.showToast('success', '成功', '收款确认成功');
              results.modalInstance.hide();
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  // 取消确认收款
  unConfirmPayment(paymentId: number) {
    const results = this.DialogService.open({
      id: 'unconfirm-payment-dialog',
      width: '400px',
      maxHeight: '600px',
      title: '取消确认',
      content: '确定要取消确认此笔收款吗？',
      dialogtype: 'standard',
      buttons: [
        {
          cssClass: 'primary',
          text: '确认',
          disabled: false,
          handler: ($event: Event) => {
            // 在实际项目中这里应该调用API
            const payment = this.tableData.find((item: any) => item.salePaymentId === paymentId);
            if (payment) {
              payment.isConfirmed = false;
              payment.status = '待确认';
              payment.confirmDate = null;
              payment.confirmer = '';

              this.showToast('success', '成功', '取消确认成功');
              results.modalInstance.hide();
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
